import Layout from '@/layouts/BasicLayout/index.vue'
let routeModules = import.meta.glob('/src/views/**/*.vue')

import { setConfig } from '@/config'

export const generator = (arr) => {
    arr.map((item) => {
        item.meta = {
            title: item.title,
            keepAlive: item.keepAlive,
            activeName: item.activeName || undefined,
        }
        if (item.children && item.children.length) {
            item.redirect = item.children[0].path
        }
        if (item.component) {
            if (routeModules[`/src${item.component}.vue`]) {
                item.component = routeModules[`/src${item.component}.vue`]
            } else {
                //组件不存在时，给默认组件
                item.component = routeModules[`/src/views/ErrorPage/err.vue`]
            }
        }

        if (item.children) generator(item.children)
        return item
    })
    return arr
}

// 根路由，设置basicLayout
const rootRouter = {
    path: '/BasicLayout',
    name: 'BasicLayout',
    meta: {
        title: '主页',
    },
    component: Layout,
    redirect: '',
    children: [],
}

const pathMatch = {
    path: '/:pathMatch(.*)*',
    redirect: '/404',
}

export const generatorDynamicRouter = async (data) => {
    const menuNav = data
    let routers = []
    if (!data.length) return []
    const _routers = await generator(menuNav)
    //菜单路由
    let isMenus = _routers.filter(v => v.isMenu)
    rootRouter.children = isMenus
    rootRouter.redirect = data[0].path
    //设置重定向页面
    setConfig('redirectPath', data[0].path)
    routers.push(rootRouter)
    //非菜单路由
    _routers.filter(v => !v.isMenu).forEach(v => {
        routers.push(v)
    });
    routers.push(pathMatch)

    return routers
}
